package odometerDevice.connectionDevice.android;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

import javax.microedition.io.StreamConnection;

import odometerDevice.connectionDevice.android.bluetooth.RequestConnection;

public class SansungI9000 implements IAndroidConnection {

    private StreamConnection connection;
    private InputStream inputStream;
    private OutputStream outputSream;

    private byte[] readValues = new byte[4];

    @Override
    public void open() throws IOException {

	connection = new RequestConnection().getConnection();
	inputStream = connection.openInputStream();
	outputSream = connection.openOutputStream();
    }

    @Override
    public boolean isConnected() {
	return connection != null;
    }

    @Override
    public void close() {
	try {
	    inputStream.close();
	    outputSream.close();
	    connection.close();
	} catch (IOException ioe) {
	    System.out.println("IOException closing connection:");
	    System.out.println(ioe.getMessage());
	}
    }

    @Override
    public byte[] read() {
	try {
	    inputStream.read(readValues, 0, 4);
	    return readValues;
	} catch (IOException ioe) {
	    System.out.println("SansungI9000 - IO Exception reading bytes:");
	    System.out.println(ioe.getMessage());
	    close();
	    return null;
	}
    }

    @Override
    public void write(byte[] values) {
	try {
	    outputSream.write(values);
	    outputSream.flush();

	} catch (IOException ioe) {
	    System.out.println("IO Exception writing bytes:");
	    System.out.println(ioe.getMessage());
	    close();
	}
    }

    public int getOrientation() {

	return ByteBuffer.wrap(read()).getInt();
    }

}
